
#import "HttpRequest.h"

#define POST_BOUNDS @"9"
typedef enum _TYPE {
    GETRequest = 0,
    POSTRequest = 1
} TYPE;

@implementation HttpRequest

+ (instancetype)currentHttpRequest
{
    static id request = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        request = [[self alloc] init];
    });
    return request;
}

- (void)hideHUD
{
    for (id view in [UIApplication sharedApplication].keyWindow.subviews)
    {
        if ([view isKindOfClass:[MBProgressHUD class]])
        {
            MBProgressHUD *hud = view;
            [hud hideAnimated:YES];
        }
    }
}

- (void)showHUDWithMessage:(NSString *)message
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.bezelView.backgroundColor = UIColorFromHex(0xFF9D9D9D);
    hud.contentColor = [UIColor whiteColor];
    hud.label.text = NSLocalizedString(message, nil);
    hud.label.font = FontWithSize(12);
    [hud hideAnimated:YES afterDelay:HUDTime];
}

//判断session是否失效
- (BOOL)isSessionExist
{
    [self postPath:CheckSession params:nil resultBlock:^(id Data, MsgModel *msgModel) {
        
    }];
    return NO;
}

- (void)postPath:(NSString *)path
          params:(id)params
     resultBlock:(ResultHttpBlock)resultBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes =  [NSSet setWithObjects:@"application/json", @"text/javascript", @"text/html",@"application/x-www-form-urlencoded", nil];
    if ([path isEqualToString:Login] || [path isEqualToString:GetVerifyCode_API]) {
        
    }else
    {
        [manager.requestSerializer setValue:[NSString stringWithFormat:@"SESSION=%@",USER_DEFAULTS_GET(LoginStatue)] forHTTPHeaderField:@"Cookie"];
    }
    
    //新增请求头 版本号和设备类型
    [manager.requestSerializer setValue:@"seller-app@ios" forHTTPHeaderField:@"yb-c-t"];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic valueForKey:@"CFBundleShortVersionString"];
    [manager.requestSerializer setValue:currentVersion forHTTPHeaderField:@"yb-c-v"];
    
    NSString *urls = [NSString stringWithFormat:@"%@%@",URL_HOST,path];
    NSLog(@"urls:%@---params:%@",urls,params);
    
    [manager POST:urls parameters:params progress:^(NSProgress * _Nonnull uploadProgress)
    {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
//        NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
//        NSDictionary *allHeaderFields = response.allHeaderFields;
//        NSString *Authorization = allHeaderFields[@"Authorization"];
//        NSLog(@"Authorization--%@",Authorization);

        NSLog(@"responseObject-%@",responseObject);
        MsgModel *model = [[MsgModel alloc] init];
        model.status = [(NSString *)responseObject[@"code"] integerValue];
        if ([path isEqualToString:CHANGEPRICEGOODS_API])
        {
            NSDictionary *attributes = (NSDictionary *)responseObject[@"attributes"];
            NSString *changeCount = attributes[@"changeCount"];
            model.changeCount = [changeCount intValue];
        }
        //当接口是店铺状态的时候
        
        if ([path isEqualToString:RemoveRecommend_API]||
                 [path isEqualToString:AddRecommend_API]||
                 [path isEqualToString:EditGoods_API]||
                 [path isEqualToString:CheckSignResult_API]||
                 [path isEqualToString:ShopState_API])
        {
            if (model.status == 200)
            {
                resultBlock(responseObject,model);
            }
        }
        else
        {
            if (model.status == 200)
            {//请求成功
                resultBlock(responseObject[@"result"],model);
            }
            //调登陆
            else if (model.status == 401)
            {
                LoginController *login = [LoginController new];
                AppDelegate* app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                app.window.rootViewController = login;
            }
            else {
                [self hideHUD];
                model.message = responseObject[@"message"];
                if (NOEmptyStr(model.message))
                {
                    NSLog(@"请求失败描述--%@",model.message);
                    [self showHUDWithMessage:model.errorCode];
                }
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        NSString *errorStr = error.description;
        NSLog(@"连接失败描述：%@",errorStr);
        [self hideHUD];
        [self showHUDWithMessage:@"请求异常，请检查网络连接状态"];
    }];
}

-(void)getPath:(NSString *)path
        params:(id)params
   resultBlock:(ResultHttpBlock)resultBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",  nil];
    manager.requestSerializer.timeoutInterval = 20;
    
    //新增请求头 版本号和设备类型
    [manager.requestSerializer setValue:@"seller-app@ios" forHTTPHeaderField:@"yb-c-t"];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic valueForKey:@"CFBundleShortVersionString"];
    [manager.requestSerializer setValue:currentVersion forHTTPHeaderField:@"yb-c-v"];
    
    NSString *urls = [NSString stringWithFormat:@"%@%@",URL_HOST,path];
    NSLog(@"urls:%@---params:%@",urls,params);
    
    [manager GET:urls parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        MsgModel *model = [[MsgModel alloc] init];
        model.status = [(NSString *)responseObject[@"code"] integerValue];
        
        if (model.status == 200)
        {//请求成功
            resultBlock(responseObject[@"result"],model);
        }
        else {
            [self hideHUD];
            model.message = responseObject[@"message"];
            if (NOEmptyStr(model.message))
            {
                NSLog(@"请求失败描述--%@",model.message);
                [self showHUDWithMessage:model.errorCode];
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        NSString *errorStr = error.description;
        NSLog(@"连接失败描述：%@",errorStr);
        [self hideHUD];
        [self showHUDWithMessage:@"请求异常，请检查网络连接状态"];
    }];
}

- (void)putPath:(NSString *)path params:(id)params resultBlock:(ResultHttpBlock)resultBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json",@"text/html",  nil];
    manager.requestSerializer.timeoutInterval = 20;
    
    
    NSString *urls = [NSString stringWithFormat:@"%@%@",URL_HOST,path];
    NSLog(@"urls:%@---params:%@",urls,params);
    [manager PUT:urls parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
        MsgModel *model = [[MsgModel alloc] init];
        model.status = [(NSString *)responseObject[@"code"] integerValue];
        
        
        if (model.status == 200)
        {//请求成功
            resultBlock(responseObject[@"result"],model);
        }
        else {
            [self hideHUD];
            model.message = responseObject[@"message"];
            if (NOEmptyStr(model.message))
            {
                NSLog(@"请求失败描述--%@",model.message);
                [self showHUDWithMessage:model.errorCode];
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        NSString *errorStr = error.description;
        NSLog(@"连接失败描述：%@",errorStr);
        [self hideHUD];
        [self showHUDWithMessage:@"请求异常，请检查网络连接状态"];
    }];
}

- (void)uploadWithParams:(id)params andImageData:(NSData*)data block:(void (^)(NSString *SamllPhoto))block
{
    NSLog(@"params:%@",params);
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:
                                                         @"application/json",
                                                         @"text/json",
                                                         @"text/javascript",
                                                         @"text/html",
                                                         @"text/plain",
                                                         nil];
//    NSInteger timeInterval = [[NSDate date] timeIntervalSince1970] * 1000;
//    NSString *key = [NSString stringWithFormat:@"CityWide.Auth-%ld-TimeStampCityWide.Auth-Pass-Key",(long)timeInterval];
//    [manager.requestSerializer setValue:[self MD5WithString:key] forHTTPHeaderField:@"Auth-Pass-Key"];
//    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%ld",(long)timeInterval] forHTTPHeaderField:@"Auth-Time-Stamp"];
     [manager.requestSerializer setValue:[NSString stringWithFormat:@"SESSION=%@",USER_DEFAULTS_GET(LoginStatue)] forHTTPHeaderField:@"Cookie"];
    NSString *urls = [NSString stringWithFormat:@"%@%@",URL_HOST,UploadImage_API];
    [manager POST:urls parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:data name:@"file"
                                fileName:@"headImage.png" mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
       //  NSLog(@"service progress...");
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          if (responseObject != nil) {
              NSLog(@"upload-responseObject==%@",responseObject);
              MsgModel *model = [[MsgModel alloc] init];
              model.status = [(NSString *)responseObject[@"code"] integerValue];
              if (model.status == 200)
              {
                  NSLog(@"请求成功");
                  block(responseObject[@"result"]);
              }
          }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSString *errorStr = error.description;
        NSLog(@"连接失败描述：%@",errorStr);
    }];
    /*
    [manager POST:urls parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
         NSLog(@"upload-responseObject--%@",responseObject);
        
        
         MsgModel *model = [[MsgModel alloc] init];
         model.status = [(NSString *)responseObject[@"code"] integerValue];
        
        if (model.status == 200)
        {
            NSLog(@"请求成功");
        }
        else
        {
            [self hideHUD];
            model.message = responseObject[@"message"];
            if (NOEmptyStr(model.message))
            {
                NSLog(@"请求失败描述--%@",model.message);
                [self showHUDWithMessage:model.errorCode];
            }
        }
     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error)
    {
        NSString *errorStr = error.description;
        NSLog(@"连接失败描述：%@",errorStr);
        [self hideHUD];
        [self showHUDWithMessage:@"请求异常，请检查网络连接状态"];
     }];
     */
}

#pragma mark -- 表单模式
+(void)formPostPath:(NSString *)myUrl
       params:(NSMutableDictionary *)dicData
  resultBlock:(ResultHttpBlock)resultBlock
{
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",URL_HOST,myUrl]];
    NSLog(@"接口地址是%@",url);
    NSMutableString *bodyContent = [NSMutableString string];
    for(NSString *key in dicData.allKeys){
        id value = [dicData objectForKey:key];
        [bodyContent appendFormat:@"--%@\r\n",POST_BOUNDS];
        [bodyContent appendFormat:@"Content-Disposition:form-data; name=\"%@\"\r\n\r\n",key];
        [bodyContent appendFormat:@"%@\r\n",value];
    }
    [bodyContent appendFormat:@"--%@--\r\n",POST_BOUNDS];
    NSData *bodyData=[bodyContent dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
    //cookie的获取
    if ([myUrl isEqualToString:Login] || [myUrl isEqualToString:GetVerifyCode_API])
    {
        
    }else
    {
        [request setValue:[NSString stringWithFormat:@"SESSION=%@",USER_DEFAULTS_GET(LoginStatue)] forHTTPHeaderField:@"Cookie"];
          NSLog(@"session=%@",USER_DEFAULTS_GET(LoginStatue));
    }
    //新增请求头 版本号和设备类型
    [request setValue:@"seller-app@ios" forHTTPHeaderField:@"yb-c-t"];
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic valueForKey:@"CFBundleShortVersionString"];
    [request setValue:currentVersion forHTTPHeaderField:@"yb-c-v"];
    
    [request addValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",POST_BOUNDS] forHTTPHeaderField:@"Content-Type"];
//    [request addValue:@"application/x-www-form-urlencoded ;charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [request addValue: [NSString stringWithFormat:@"%zd",bodyData.length] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPMethod:@"POST"];
   // [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Accept"];
    [request setHTTPBody:bodyData];
    NSLog(@"请求的长度%@",[NSString stringWithFormat:@"%zd",bodyData.length]);
    __autoreleasing NSError *error=nil;
    __autoreleasing NSURLResponse *response=nil;
    NSLog(@"输出Bdoy中的内容>>\n%@",[[NSString alloc]initWithData:bodyData encoding:NSUTF8StringEncoding]);
    NSData *reciveData= [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (reciveData == nil)
    {
        return;
    }
    NSDictionary *data = [NSJSONSerialization JSONObjectWithData:reciveData options:NSJSONReadingMutableContainers error:&error];
    if(error){
        MsgModel *model = [[MsgModel alloc] init];
        model.status = [(NSString *)data[@"code"] integerValue];
        if (model.status == 401) {
            resultBlock(data,model);
        }
        NSLog(@"出现异常%@",error);
    }else
    {
        NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
        NSDictionary *allHeaders = httpResponse.allHeaderFields;
        NSString *session = allHeaders[@"S-Session"];
        NSString *localSession = USER_DEFAULTS_GET(LoginStatue);
        if (![localSession isEqualToString:session])
        {
             USER_DEFAULTS_SAVE(session, LoginStatue);
        }
        if (httpResponse.statusCode == 404) {
            MsgModel *model = [[MsgModel alloc] init];
            model.status = [(NSString *)data[@"code"] integerValue];
            resultBlock(data,model);
        }
        else if(httpResponse.statusCode==200)
        {
            //[[NSString alloc]initWithData:reciveData encoding:NSUTF8StringEncoding]
            NSLog(@"服务器成功响应!>>%@",data);
            MsgModel *model = [[MsgModel alloc] init];
            model.status = [(NSString *)data[@"code"] integerValue];
            
            //401跳转登录
             if (model.status == 401)
            {
                LoginController *login = [LoginController new];
                AppDelegate* app = (AppDelegate *)[UIApplication sharedApplication].delegate;
                app.window.rootViewController = login;
            }else
            {
                if ([myUrl isEqualToString:Login ]||
                    [myUrl isEqualToString:OrderList_API]||
                    [myUrl isEqualToString:ShopState_API] ||
                    [myUrl isEqualToString:GetByCode_API]||
                    [myUrl isEqualToString:Capital_API]||
                    [myUrl isEqualToString:AddRecommend_API])
                {
                    resultBlock(data,model);
                }else
                {
                    if (model.status == 200)
                    {//请求成功
                        resultBlock(data,model);
                    }
                    else
                    {
                        [TTKUtil hudShowMessage:data[@"message"]];
                    }
                }
            }
        }else{
            NSLog(@"服务器返回失败>>%@",data);
            NSLog(@"失败--%@",data[@"message"]);
            [TTKUtil hudShowMessage:data[@"message"]];
        }
    }
}

@end


@implementation MsgModel
@end
